package org.ru.mse10.cvis.service.search;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.ru.mse10.cvis.constants.UserRole;
import org.ru.mse10.cvis.dto.user.UserSearchDTO;
import org.ru.mse10.cvis.entity.cv.User;
import org.ru.mse10.cvis.util.CommonUtil;

/**
 * The Class UserSearcher.
 */
public class UserSearcher extends EntitySearcher<User, UserSearchDTO> {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.ru.mse10.cvis.service.search.EntitySearcher#appendCriteria(javax.
	 * persistence.criteria.CriteriaBuilder,
	 * javax.persistence.criteria.CriteriaQuery,
	 * javax.persistence.criteria.Root, org.ru.mse10.cvis.dto.BaseDTO)
	 */
	@Override
	protected <X> void appendCriteria(CriteriaBuilder qb, CriteriaQuery<X> c,
			Root<User> p, UserSearchDTO dto) {
		List<Predicate> criteria = new ArrayList<Predicate>();
		if (!CommonUtil.isEmpty(dto.getEmail())) {
			criteria.add(qb.equal(p.<String> get("email"), dto.getEmail()));
		}
		if (!CommonUtil.isEmpty(dto.getName())) {
			criteria.add(qb.like(p.<String> get("name"), "%" + dto.getName()
					+ "%"));
		}
		if (!CommonUtil.isEmpty(dto.getMiddleName())) {
			criteria.add(qb.like(p.<String> get("middleName"),
					"%" + dto.getMiddleName() + "%"));
		}
		if (!CommonUtil.isEmpty(dto.getLastName())) {
			criteria.add(qb.like(p.<String> get("lastName"),
					"%" + dto.getLastName() + "%"));
		}
		if (!CommonUtil.isEmpty(dto.getRoles())) {
			In<UserRole> in = qb.in(p.<UserRole> get("role"));
			for (UserRole type : dto.getRoles()) {
				in.value(type);
			}
			criteria.add(in);
		}
		c.where(criteria.toArray(new Predicate[] {}));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.ru.mse10.cvis.service.search.EntitySearcher#getEntityClass()
	 */
	@Override
	public Class<User> getEntityClass() {
		return User.class;
	}

}
